from flask import Flask,render_template, request, jsonify, send_file
from application.sootang import get_result
from application.cospa import get_cospa_result,create_zip,get_bconline_result
from application.bloom import get_bloom_result
from application.excel import get_excel_num,get_excel_data
import os
from datetime import datetime
from werkzeug.utils import secure_filename

# 创建Flask实例
app = Flask(__name__)
 
# 定义sootang路由
@app.route('/')
def index():
    return  render_template("index.html")

@app.route('/getData', methods=['POST'])
def getData():
    data = request.get_json()
    barcode = data['barcode']
    
    timestamp = data['cutOffTimeEnd']
    result = get_result(data)
    # print(barcode,barcode.split("\n"),result)
    # exit()
    if result:
        return jsonify({'code':200, 'message': 'Data received successfully!','data':result})
    else:
        return jsonify({'code':500, 'message': 'Data received fail!'})


@app.route('/download/<filename>')
def download_file(filename):
    date = request.args.get('date')
    image_folder = 'download/sootang/'+ date + '/' + filename
    return send_file(image_folder, as_attachment=True)


@app.route('/getCospaData', methods=['POST'])
def getCospaData():
    data = request.get_json()
    barcode = data['barcode']
    type = int(data['type'])
    if type == 1 :
        result = get_cospa_result(data)
    else :
        result = get_bloom_result(data)
    if result:
        return jsonify({'code':200, 'message': 'Data received successfully!','data':result})
    else:
        return jsonify({'code':500, 'message': 'Data received fail!'})

@app.route('/downloadzip/<filename>')
def download_zip_file(filename):
    zip_filename = filename + '.zip'
    date = request.args.get('date')
    type = int(request.args.get('type'))
    if type == 1:
        path = 'download/cospa/'+ date    
    else:
        path = 'download/bloom/'+ date
    folder_to_zip = path + '/' + filename
    zip_filename = path + '/' + filename + '.zip'
    create_zip(zip_filename, folder_to_zip)
    return send_file(zip_filename, as_attachment=True)

# excel文件上传
@app.route('/upload/excel', methods=['POST'])
def upload_excel():
    # 定义一个每个表格有多少数据的
    if request.method == 'POST':
        # 检查是否有文件在上传
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # print(file,file.filename)
        # exit()
        # 如果用户没有选择文件，浏览器会提交一个没有文件名的空部分
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file:
            filename = secure_filename(file.filename)
            file.save(os.path.join('upload/excel/sample', 'product1.xlsx'))
            # return f'File uploaded successfully: {filename}'
    result = get_excel_num('product1')
    if result:
        return jsonify({'code':200, 'message': 'Data received successfully!','data':result})
    else:
        return jsonify({'code':500, 'message': 'Data received fail!'})


@app.route('/getExcelData')
def get_form_data():
    sheet_data = request.args.get('every_sheet')
    sheet_data_total = sheet_data.split(",")

    result = get_excel_data(sheet_data_total,'product1')
    print(result)

    time = result['time']
    filename = time + '_export_excel_images'
    path = 'download/excel/'+ time
    folder_to_zip = path + '/'
    zip_filename = 'download/excel/' + filename + '.zip'
    create_zip(zip_filename,folder_to_zip)
    return send_file(zip_filename, as_attachment=True)

@app.route('/getBconlineData')
def getBconlineData():
    url = request.args.get('url')
    result = get_bconline_result(url)
    time = result['date']
    filename = "bc-online_" + time + '_'+ result['barcode']
    path = 'download/bc-online/'+ time
    folder_to_zip = path + '/' + result['barcode']
    zip_filename = 'download/bc-online/' + filename + '.zip'
    create_zip(zip_filename,folder_to_zip)
    return send_file(zip_filename, as_attachment=True)


if __name__ == '__main__':
    app.run(debug=True)